<template>
  <div class="app-container">
    <!-- 生成二维码 -->
    <h3 class="title">标码记录</h3>
    <!-- {{ categoryList }} -->
    <div class="inputBox">
      <el-input v-model="search.generateNumber" class="input" placeholder="请输入规则编号" />
      <el-button type="primary" class="ml10" @click="toSearch">查询</el-button>
      <el-button type="primary" @click="toReset">重置</el-button>
    </div>

    <!-- <el-button type="primary" class="addBtn" @click="add()">新增标码规则</el-button> -->

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中请稍后"
      border
      fit
      highlight-current-row>
      <template slot="empty">
        <div class="noData">暂无数据</div>
      </template>
      <el-table-column label="生成编号" width="130">
        <template slot-scope="scope">
          {{ scope.row.generateNumber }}
        </template>
      </el-table-column>
      <el-table-column label="编码规则" width="150">
        <template slot-scope="scope">
          {{ scope.row.codingRules }}
        </template>
      </el-table-column>
      <el-table-column label="生成时间">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="编码类型">
        <template slot-scope="scope">
          {{ scope.row.codingType | codingType }}
        </template>
      </el-table-column>
      <el-table-column label="生成数量">
        <template slot-scope="scope">
          {{ scope.row.quantity }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          {{ scope.row.status | statusStr }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="400">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="success"
            @click="createCode(scope.row, scope.$index)">刷新</el-button> -->
          <el-button
            size="mini"
            type="success"
            @click="createCode(scope.row, scope.$index)">下载</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
    <AddCode
      :my-index.sync="codeIndex"
      :settings-visible.sync="codeVisible"
      :dialog-data.sync="codeData"
      :setting-mode="'code'"
      @updataParent="submitFn"
    />
    <AddCode
      :my-index.sync="createCodeIndex"
      :settings-visible.sync="createCodeVisible"
      :dialog-data.sync="createCodeData"
      :setting-mode="'createCode'"
      @updataParent="createCodeFn"
    />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'

import { Message } from 'element-ui'
import { getLocalUid, setLocalUid, getLocalId, setLocalId } from '@/utils/uid'
import { getPermission } from '@/api/permission'
import { getLocalUserName, setLocalUserName } from '@/utils/uid'
import { getCodeList, addCode, delCodeRecord, createCode, createCodeList } from '@/api/source'
import { categoryQuery } from '@/api/product'
import AddCode from '@/components/source/AddCode'
import config from '@/utils/config';
import axios from 'axios'
let that
export default {
  components: { Pagination, AddCode },
  filters: {
    goodsType(num) {
      // console.log('categoryList:', this.categoryList)
      console.log('categoryList:', that.categoryList)
      that.categoryList.forEach(item => {
        if (item.id === num) {
          console.log(item.id)
          return item.name
        }
      })
    },
    codingType(num) {
      const codingMap = {
        0: '普通码',
        1: 'NFC标签'
      }
      return codingMap[num]
    },
    statusStr(num) {
      const statusMap = {
        0: '生成中',
        1: '已生成'
      }
      return statusMap[num]
    }
  },
  data() {
    return {
      // visible: false,
      remarkProptVisible: false,
      remarkProptList: [],
      remarkProptIndex: -1,
      userName: '',
      userType: -1,
      categoryList: [],
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 0,
        pageSize: 10
      },
      search: {
        generateNumber: ''
      },
      dialogTableVisible: false,
      detailIndex: -1,
      permissionShow: false, // 权限数据未到达之前按钮隐藏

      codeVisible: false, // 新增标码规则弹窗
      codeIndex: -1,
      codeData: {},

      createCodeVisible: false, // 生成标码弹窗
      createCodeIndex: -1,
      createCodeData: {},
      id: '',
      createForm: {
        number: '',
        id: ''
      }
      // permissionList: [] // 权限数据列表
    //   remarkVisible: false,
    //   remarkIndex: -1,
    //   remarkList: [],

    //   logistics: false, // 物流弹窗
    //   logisticsIndex: -1,
    //   orderSn: '',

    //   sendGoodsVisible: false, // 发货弹窗
    //   sendGoodsIndex: -1,
    //   sendGoodsData: {}

    }
  },
  computed: {
    // permissionBoolean() {
    //   return function(str) {
    //     const arr = []
    //     for (let i = 0; i < this.permissionList.length; i++) {
    //       arr.push(this.permissionList[i].name)
    //     }
    //     const index = arr.indexOf(str)

    //     if (index !== -1) {
    //       return true
    //     } else {
    //       return false
    //     }
    //   }
    // }
  },
  watch: {
    'permissionList'(newVal) {
      this.permissionList = newVal
      this.permissionShow = true
    }
  },
  beforeCreate() {
    that = this
  },
  created() {
    if (this.$route.query && JSON.stringify(this.$route.query) !== '{}') {
      console.log(this.$route.query.id)
      this.createForm.id = this.$route.query.id
    }
    // console.log('userType:', this.userType)
    // this.getPermissonFn()
  },
  mounted() {
    this.getUserType()
    this.getCategory()
    this.fetchData()
  },
  methods: {
    // 权限数据的获取
    // getPermissonFn() {
    //   const id = getLocalId()
    //   const uid = getLocalUid()
    //   const data = { uid }
    //   getPermission(id, data).then(res => {
    //     console.log('权限结果', res)
    //     if (res.code === '200') {
    //       this.permissionList = res.data
    //       // console.log('权限名称：', this.getPermissionName(this.permissionList))
    //     } else {
    //       Message.error(res.message + '-' + res.data)
    //     }
    //   })
    // },
    exportZip() {
      axios({
        method: 'get',
        url: config.BaseUrl + '/code/downloadCode',
        params: this.createForm,
        responseType: 'blob'
      }).then((res) => {
        // const blob = new Blob([res.data], { type: 'application/zip' })
        // const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        link.href = res.request.responseURL
        // link.download = '清单文件' // 重命名文件
        link.click()
      }).catch(err => {
        this.$Message.error(err)
      })
      // this.exportZip()
    },
    // 点击列表中 下载 按钮
    createCode(row, index) {
    //   this.createCodeVisible = true
    //   this.createCodeData = row
    //   this.createCodeIndex = index
      this.createForm.id = row.id
      // this.createForm.number = row.quantity // 生成数量
      this.exportZip()
    },

    createCodeFn(val) {
      // console.log('this.val:', val)
      createCode(val).then(res => {
        if (res.code === '200') {
          Message.success('新增成功')
        //   this.fetchData()
        }
      })
    },
    submitFn(val) {
      console.log('this.codeIndex:', this.codeIndex)
      addCode(val).then(res => {
        if (res.code === '200') {
          Message.success('新增成功')
          this.fetchData()
        } else {
          Message.error(res.message + '-' + res.data)
        }
      })
    },
    add() {
      this.codeVisible = true
      // codeIndex
      // codeData
    },
    edit(row, index) {
      this.codeVisible = true
      this.codeData = row
      this.codeIndex = index
    },
    del(id) {
      this.$confirm('您确定删除此标码规则？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        delCodeRecord({ id }).then(res => {
          if (res.code === '200') {
            Message.success('已删除')
            this.fetchData()
          }
        })
      })
    },
    // 获取所有分类信息
    getCategory() {
      categoryQuery().then(res => {
        console.log('获取所有分类信息:', res)
        if (res.code === '200') {
          this.categoryList = res.data
        }
      })
    },
    getUserType() {
      switch (getLocalUserName()) {
        case 'admin':
          this.userType = 1
          break;
        case 'sale':
          this.userType = 2
          break;
        case 'casher':
          this.userType = 3
          break;
      }
    },
    // 查询
    toSearch() {
    //   if (this.search.startTime && this.search.endTime) {
    //     const start = new Date(this.search.startTime).getTime();
    //     const end = new Date(this.search.endTime).getTime();
    //     if (start > end) {
    //       Message.error('结束时间必须大于开始时间')
    //       return false
    //     }
    //   }
    //   if (this.search.startTime && this.search.startTime.indexOf(' 00:00:00') === -1) this.search.startTime += ' 00:00:00'
    //   if (this.search.endTime && this.search.endTime.indexOf(' 23:59:59') === -1) this.search.endTime += ' 23:59:59'
    //   if (this.search.startTime && this.search.endTime) {
    //     const start = new Date(this.search.startTime).getTime();
    //     const end = new Date(this.search.endTime).getTime();
    //     if (start > end) {
    //       Message.error('结束时间必须大于开始时间')
    //       return false
    //     }
    //   }
    //   if (this.search.startTime) this.search.startTime
    //   if (this.search.endTime) this.search.endTime
      this.listLoading = true
      console.log(this.search)
      const newData = Object.assign(this.listQuery, this.search, { codeId: this.createForm.id })
      createCodeList(newData).then(response => {
        if (response.code === '200') {
          this.list = response.data.list
          this.total = response.data.total
        } else {
          Message.error(response.message + '-' + response.data)
        }
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // 重置
    toReset() {
      this.search.generateNumber = ''
    },
    fetchData() {
      this.listLoading = true
      const newData = Object.assign({}, this.listQuery, { codeId: this.createForm.id })
      createCodeList(newData).then(response => {
        if (response.code === '200') {
          this.list = response.data.list
          console.log('订单数据：', this.list)
          this.total = response.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 0.5 * 1000)
        } else {
          this.listLoading = false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .inputBox{
    div{ margin-bottom: 10px;}
    .input:nth-of-type(1){ width: 200px }
    .input:nth-of-type(2){ width: 160px }
    .input:nth-of-type(3){ width: 160px }
    .input:nth-of-type(4){ width: 180px }
    .startDate, .endDate{ width: 180px }
    .input:nth-of-type(7){width:140px}
  }
  .addBtn{
      margin-bottom: 20px;
  }
</style>
